package com.zxq.ai.infrastructure.gateway;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class KimiGatewayImpl {

    public static void main(String[] args) throws IOException {
        String apiKey = "sk-PIZqFFOxgRm1xYyYnB4yxfqni1DsZ07bwugq5eLvvJZKpscG";
        String baseUrl = "https://api.moonshot.cn/v1";
        String model = "moonshot-v1-8k";
        String prompt = "你好，我叫李雷，1+1等于多少？";

        URL url = new URL(baseUrl + "/chat/completions");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer " + apiKey);
        conn.setRequestProperty("Content-Type", "application/json");

        String jsonInputString = "{\"model\": \"" + model + "\", \"messages\": [{\"role\": \"user\", \"content\": \"" + prompt + "\"}]}";

        conn.setDoOutput(true);
        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = jsonInputString.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        int responseCode = conn.getResponseCode();
        System.out.println("POST Response Code :: " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine = null;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.out.println(response.toString());
            }
        } else {
            System.out.println("POST request not worked");
        }
    }
}